package com.example.movie.ui.user.fragment

import android.content.pm.ActivityInfo
import android.view.View
import android.widget.FrameLayout
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.OnChildAttachStateChangeListener
import com.dueeeke.videocontroller.StandardVideoController
import com.dueeeke.videocontroller.component.*
import com.dueeeke.videoplayer.exo.ExoMediaPlayer
import com.dueeeke.videoplayer.player.VideoView
import com.dueeeke.videoplayer.player.VideoView.SimpleOnStateChangeListener
import com.example.movie.R
import com.example.movie.ui.user.adapter.VideoRecyclerViewAdapter
import com.example.movie.ui.user.adapter.VideoRecyclerViewAdapter.VideoHolder
import com.example.movie.ui.user.listener.OnItemChildClickListener
import com.example.movie.utils.Utils.removeViewFormParent
import com.example.movie.utils.VideoBean
import com.example.movie.utils.cache.ProxyVideoCacheManager
import com.example.movie.utils.video.Tag
import java.util.*

/**
 * RecyclerView video
 */
open class RecyclerViewFragment : BaseFragment(), OnItemChildClickListener {

    protected var mVideos: MutableList<VideoBean> = ArrayList()
    protected var mAdapter: VideoRecyclerViewAdapter? = null

    protected lateinit var mRecyclerView: RecyclerView
    private var mLinearLayoutManager: LinearLayoutManager? = null

    protected lateinit var mVideoView: VideoView<*>

    @JvmField
    protected var mController: StandardVideoController? = null

    @JvmField
    protected var mErrorView: ErrorView? = null

    @JvmField
    protected var mCompleteView: CompleteView? = null

    @JvmField
    protected var mTitleView: TitleView? = null

    /**
     * 当前播放的位置
     */
    @JvmField
    protected var mCurPos = -1

    /**
     * 上次播放的位置，用于页面切回来之后恢复播放
     */
    @JvmField
    protected var mLastPos = mCurPos


    override fun getLayoutResId(): Int {
        return R.layout.fragment_recycler_view
    }

    override fun initView() {
        super.initView()
        initVideoView()
        //保存进度
//        mVideoView.setProgressManager(new ProgressManagerImpl());
        mRecyclerView = findViewById(R.id.rv)
        mLinearLayoutManager = LinearLayoutManager(context)
        mRecyclerView.layoutManager = mLinearLayoutManager
        mAdapter = VideoRecyclerViewAdapter(mVideos)
        mAdapter!!.setOnItemChildClickListener(this)
        mRecyclerView.adapter = mAdapter
        mRecyclerView.addOnChildAttachStateChangeListener(object :
            OnChildAttachStateChangeListener {
            override fun onChildViewAttachedToWindow(view: View) {}
            override fun onChildViewDetachedFromWindow(view: View) {
                val playerContainer = view.findViewById<FrameLayout>(R.id.player_container)
                val v = playerContainer.getChildAt(0)
                if (v != null && v === mVideoView && !mVideoView!!.isFullScreen) {
                    releaseVideoView()
                }
            }
        })

//        View view = findViewById(R.id.add);
//        view.setVisibility(View.VISIBLE);
//        view.setOnClickListener(v -> mAdapter.addData(DataUtil.getVideoList()));
    }

    protected open fun initVideoView() {
        mVideoView = VideoView<ExoMediaPlayer>(requireActivity())
        mVideoView.setOnStateChangeListener(object : SimpleOnStateChangeListener() {
            override fun onPlayStateChanged(playState: Int) {
                //监听VideoViewManager释放，重置状态
                if (playState == VideoView.STATE_IDLE) {
                    removeViewFormParent(mVideoView)
                    mLastPos = mCurPos
                    mCurPos = -1
                }
            }
        })
        mController = StandardVideoController(requireActivity())
        mErrorView = ErrorView(activity)
        mController!!.addControlComponent(mErrorView)
        mCompleteView = CompleteView(requireActivity())
        mController!!.addControlComponent(mCompleteView)
        mTitleView = TitleView(requireActivity())
        mController!!.addControlComponent(mTitleView)
        mController!!.addControlComponent(VodControlView(requireActivity()))
        mController!!.addControlComponent(GestureView(requireActivity()))
        mController!!.setEnableOrientation(true)
        mVideoView.setVideoController(mController)
    }

    override fun initData() {
        super.initData()

//        val videoList = DataUtil.getVideoList()
//        mVideos.addAll(videoList!!)
//        mAdapter!!.notifyDataSetChanged()

    }

    override fun isLazyLoad(): Boolean {
        return true
    }

    override fun onPause() {
        super.onPause()
        pause()
    }

    /**
     * 由于onPause必须调用super。故增加此方法，
     * 子类将会重写此方法，改变onPause的逻辑
     */
    protected fun pause() {
        releaseVideoView()
    }

    override fun onResume() {
        super.onResume()
        //        resume();
    }
    /**
     * 由于onResume必须调用super。故增加此方法，
     * 子类将会重写此方法，改变onResume的逻辑
     */
    //    protected void resume() {
    //        if (mLastPos == -1)
    //            return;
    //        if (MainActivity.mCurrentIndex != 1)
    //            return;
    //        //恢复上次播放的位置
    //        startPlay(mLastPos);
    //    }
    /**
     * PrepareView被点击
     */
    override fun onItemChildClick(position: Int) {
        startPlay(position)
    }

    /**
     * 开始播放
     * @param position 列表位置
     */
    protected fun startPlay(position: Int) {
        if (mCurPos == position) return
        if (mCurPos != -1) {
            releaseVideoView()
        }
        val videoBean = mVideos[position]
        //边播边存
        val proxyUrl = ProxyVideoCacheManager.getProxy(requireActivity()).getProxyUrl(videoBean.url)
        mVideoView.setUrl(proxyUrl);

//        mVideoView.setUrl(videoBean.url)
        mTitleView!!.setTitle(videoBean.title)
        val itemView = mLinearLayoutManager!!.findViewByPosition(position) ?: return
        val viewHolder = itemView.tag as VideoHolder
        //把列表中预置的PrepareView添加到控制器中，注意isPrivate此处只能为true。
        mController!!.addControlComponent(viewHolder.mPrepareView, true)
        removeViewFormParent(mVideoView)
        viewHolder.mPlayerContainer.addView(mVideoView, 0)
        //播放之前将VideoView添加到VideoViewManager以便在别的页面也能操作它
        videoViewManager.add(mVideoView, Tag.LIST)
        mVideoView.start()
        mCurPos = position
    }

    private fun releaseVideoView() {
        mVideoView.release()
        if (mVideoView.isFullScreen) {
            mVideoView.stopFullScreen()
        }
        if (requireActivity().requestedOrientation != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
            requireActivity().requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
        }
        mCurPos = -1
    }
}